package com.qiyang.common.autoconfig;

import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Feign;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.web.WebMvcRegistrations;
import org.springframework.boot.autoconfigure.web.WebMvcRegistrationsAdapter;
import org.springframework.cloud.netflix.feign.AnnotatedParameterProcessor;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * Created on 2018/5/7.
 *
 * @author sehuaqi.
 * 描述：重写 RequestMappingHandlerMapping isHandler 条件
 * 如下实现的isHandler函数继承了原来的实现，同时增加了一个条件：不能被@FeignClient注解修饰的类才会进行解析加载。
 */
@Configuration
@ConditionalOnClass({Feign.class})
public class FeignConfiguration {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired(required = false)
    private List<AnnotatedParameterProcessor> parameterProcessors = new ArrayList<>();

    Logger logger = LoggerFactory.getLogger(FeignConfiguration.class);

    @Bean
    public WebMvcRegistrations feignWebMvcRegistrations() {

        logger.info("<加载重新写的 feignWebMvcRegistrations>");

        return new WebMvcRegistrationsAdapter() {
            @Override
            public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
                return new FeignRequestMappingHandlerMapping();
            }
        };
    }

    public static class FeignRequestMappingHandlerMapping extends RequestMappingHandlerMapping {

        @Override
        protected boolean isHandler(Class<?> beanType) {
            logger.debug("<加载重写的判断是否是Mapping处理映射关系条件>");
            return super.isHandler(beanType) && !AnnotatedElementUtils.hasAnnotation(beanType, FeignClient.class);
        }

    }
}
